package com.its.common.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.*;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @Author xiaxp
 * @Date 2021-12-24 11:00
 * @Description
 */
@Slf4j
@Order(100)
public class RedissonCloseAutoConfigureProcessor implements EnvironmentPostProcessor {

    private final static String SPRING_AUTOCONFIG_EXCLUDE = "spring.autoconfigure.exclude";
    private final static String ITS_REDIS_ENABLED = "its.redis.enabled";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment,
                                       SpringApplication springApplication) {
        addDefaultPropertySource(environment);
    }

    private void addDefaultPropertySource(ConfigurableEnvironment environment) {
//        String redisEnable = environment.getProperty(ITS_REDIS_ENABLED);
//        final String TRUE = "true";
//        if(StringUtils.hasText(redisEnable) && redisEnable.contains(TRUE)){
//            return;
//        }
//        // 获取当前应用中的配置信息
//        int startInx = 0;
//        for (PropertySource<?> source : environment.getPropertySources()) {
//            if (source instanceof MapPropertySource) {
//                MapPropertySource target = (MapPropertySource) source;
//                for (String key : target.getSource().keySet()) {
//                    if(key.contains(SPRING_AUTOCONFIG_EXCLUDE)){
//                        startInx++;
//                    }
//                }
//            }
//        }
//        // 自定义修改后添加进去覆盖
//        HashMap<String, Object> map = new HashMap<>(5);
//        map.put(SPRING_AUTOCONFIG_EXCLUDE + "[" + startInx++ +"]",
//                "org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration");
//        map.put(SPRING_AUTOCONFIG_EXCLUDE + "[" + startInx++ +"]",
//                "org.redisson.spring.starter.RedissonAutoConfiguration");
//        map.put(SPRING_AUTOCONFIG_EXCLUDE + "[" + startInx++ +"]",
//                "com.its.common.redis.RedissonAutoConfigure");
////        map.put(SPRING_AUTOCONFIG_EXCLUDE + "[" + startInx++ +"]",
////                "org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration");
//        map.put(SPRING_AUTOCONFIG_EXCLUDE + "[" + startInx++ +"]",
//                "org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration");
//        PropertySource source = new MapPropertySource("redisExtendExcludes", map);
//        environment.getPropertySources().addLast(source);
    }
}
